"""This module contains classes and functions related to number theory."""

"""Project Euler Solutions Library

Copyright (c) 2011 by Robert Vella - robert.r.h.vella@gmail.com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

from euler.core import LazyEvaluatedList, infinity, whichinteger
from euler.numbers.primes import Primes
from euler.numbers.advanced_math import factors
from euler.numbers.advanced_math import quadratic_roots


def istriangle_number(n):
    """Returns true if [n] is a triangle number."""
    return whichtriangle_number(n) is not None


def whichtriangle_number(n):
    """Returns the index of [n] if [n] is a triangle number. Otherwise this
    function returns None."""
    
    return whichinteger(get_triangle_number_index(n))
        
def get_triangle_number_index(n):
    """Returns the triangle number index for [n]."""
    
    return quadratic_roots(1, 1, -2 * n)[1]

def get_triangle_number(n):
    """Returns the [n]th triangle number."""
    
    return n * (n + 1) / 2.0 

def get_pentagonal_number_index(n):
    """Returns the pentagonal number index for [n]."""
    
    return quadratic_roots(3, -1, -2 * n)[1]

def ispentagonal_number(n):
    """Returns true if [n] is a pentagonal number."""
    return whichpentagonal_number(n) is not None


def whichpentagonal_number(n):
    """Returns the index of [n] if [n] is a pentagonal number. Otherwise this
    function returns None."""
    
    return whichinteger(get_pentagonal_number_index(n))

def get_pentagonal_number(n):   
    """Returns the [n]th pentagonal number."""
    
    return n * (3 * n - 1) / 2.0

def get_hexagonal_number_index(n):
    """Returns the hexagonal number index for [n]."""
    
    return quadratic_roots(2, -1, -n)[1]

def get_hexagonal_number(n):   
    """Returns the [n]th hexagonal number."""
    
    return n * (2 * n - 1)     

       
class FibonacciList(LazyEvaluatedList):
    """A cached list of fibonacci numbers."""
    
    def __init__(self):
        LazyEvaluatedList.__init__(self, [1, 1, 2, 3, 5, 8, 13])
    
    #Override.
    def _next_item(self, last_result, number_of_known_terms):  
        return self[-2] + self[-1]
 
      
class TriangleNumbers(LazyEvaluatedList):
    """A cached list of triangle numbers."""
    
    def __init__(self):
        LazyEvaluatedList.__init__(self, [1, 3, 6, 10, 15, 21, 28, 36, 45, 55])
    
    #Override.
    def _next_item(self, last_result, number_of_known_terms):
        n = len(self.terms()) + 1
        return get_triangle_number(n)


class PentagonalNumbers(LazyEvaluatedList):
    """A cached list of pentagonal numbers."""
    
    def __init__(self):
        LazyEvaluatedList.__init__(self, [1, 5, 12, 22, 35])
  
    #Override.
    def _next_item(self, last_result, number_of_known_terms):
        n = len(self.terms()) + 1
        return get_pentagonal_number(n)
    
    
class HexagonalNumbers(LazyEvaluatedList):
    """A cached list of hexagonal numbers."""
    
    def __init__(self):
        LazyEvaluatedList.__init__(self, [1, 6, 15, 28, 45])
  
    #Override.
    def _next_item(self, last_result, number_of_known_terms):
        n = len(self.terms()) + 1
        return get_hexagonal_number(n)


class AbundantNumbers(LazyEvaluatedList):
    """A cached list of abundant numbers. That is, numbers for which the
    sum of their factors exceeds their second multiple.
    """
    
    def __init__(self, primes = None, precal = 0):
        """Optional Parameters:
            primes - An already active prime cache 
                        (See: euler.numbers.primes.Primes), as this algorithm 
                   depends on the generation of prime numbers, passing an instance
                   of Primes, with a number of pre-generated results, will actually
                   reduce execution time. New primes generated within this class
                   will also be added to the cache.
        """
        
        self._primes = primes or Primes()
        LazyEvaluatedList.__init__(self, [12], precal)
    
    #Override.
    def _next_item(self, last_result, number_of_known_terms):
        for i in infinity(last_result + 1):
            if isabundant(i, self):
                return i

         
def isabundant(n, abundant_numbers = None):
    """Returns true if [n] is an abundant number. That is, a number for which 
    the sum of its factors exceeds its second multiple.
    
    
    Optional Parameters:
        abundant_numbers - An already active abundant numbers cache 
                    (See: euler.numbers.number_theory.AbundantNumbers), in 
                order to save time, this function checks if the abundant number 
                is already present in the cache.
    """
    
    #Return true if a cache has been passed and if [n] is already present in 
    #the cache.
    
    if abundant_numbers is not None and n < abundant_numbers[-1]:
        if n in abundant_numbers.terms():
            return True
        else:
            return False
       
    #According to the known properties of abundant numbers, the smallest 
    #abundant number not divisable by 3 or 2 is 5,391,411,025. Also, the 
    #smallest abundant number which is not divisable by 2 is 945. Make sure 
    #that [n] satisfies these properties before going further.
    if n < 945 and n % 2 != 0:
        return False
    
    if n > 945 and n < 5391411025 and n % 3 != 0 and n % 2 != 0:
        return False
    
    #Return true if the sum of factors of [n] > 2n.
    return sum(factors(n, abundant_numbers._primes)) > n * 2

class AmicablePairs(LazyEvaluatedList):
    """A cached list of amicable pair. That is, pair of numbers for which 
    the sum of proper divisors of one number equals the other number.
    """
    
    def __init__(self, primes = None, precal = 0):
        """Optional Parameters:
            primes - An already active prime cache 
                        (See: euler.numbers.primes.Primes), as this algorithm 
                   depends on the generation of prime numbers, passing an instance
                   of Primes, with a number of pre-generated results, will actually
                   reduce execution time. New primes generated within this class
                   will also be added to the cache.
        """
        
        LazyEvaluatedList.__init__(self, [(220, 284)], precal)
        self.primes = primes or Primes()
    
    #Override.
    def _next_item(self, last_result, number_of_known_terms):
        #Go through all the values of n > last amicable number found until
        #a new amicable pair is found.
        for n in infinity(last_result[1] + 1):
            sum_of_proper_divisors = sum(factors(n, self.primes)) - n 
            
            #Numbers which are equal to their own sum of proper divisors
            #are skipped, as those are perfect numbers.
            if n == sum(factors(sum_of_proper_divisors, self.primes)) \
                - sum_of_proper_divisors and n != sum_of_proper_divisors:
                
                return (n, sum_of_proper_divisors)
            
